<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<title>Document</title>
		<style>
			h3 {
				text-align: center;
				cursor: pointer;
			}
			
			.wrap {
				width: 600px;
				margin: 50px auto;
				text-align: center;
				cursor: pointer;
			}
			
			button {
				height: 100px;
				width: 30px;
				border-radius: 5px;
			}
			
			.active {
				background: green;
				color: #ffffff;
			}
		</style>
	</head>

	<body>
		<h3 onclick="autoPlay();">电子琴 (点击弹奏)</h3>
		<div id="box" class="wrap">
			<button>1</button>
			<button>2</button>
			<button>3</button>
			<button>4</button>
			<button>5</button>
			<button>6</button>
			<button>7</button>
		</div>

		<div id="music" class="music">
			<audio src="music/1.mp3"></audio>
			<audio src="music/2.mp3"></audio>
			<audio src="music/3.mp3"></audio>
			<audio src="music/4.mp3"></audio>
			<audio src="music/5.mp3"></audio>
			<audio src="music/6.mp3"></audio>
			<audio src="music/7.mp3"></audio>
		</div>
	</body>
</html>

<script type="text/javascript">
	var box = document.getElementById('box');
	var music = document.getElementById('music');

	box.onclick = function() {
		var target = event.target;
		// 如果点到了box而不是button,就返回
		if(target.id === 'box') return false;
		var activeEl = document.querySelector('.active');
		// 等同于上面的if语句
		activeEl && activeEl.classList.remove('active');
		// 给点击的目标添加acitve类,改变背景颜色
		target.classList.add('active');
		// 获取点击的按钮上的数值
		var num = target.innerText;
		// 根据数值播放对应的音乐
		var au = music.children[num - 1];
		// 如果正在播放,就重新播放
		if(au.played) {
			au.currentTime = 0;
		}
		au.play();
	}

	var buttons = box.children;
	// 自动播放
	function autoPlay() {
		// 小星星
				var keys = [3, 3, 4, 5, 0, 5, 4, 3, 2, 0, 1, 1, 2, 3, 0, 3, 2, 2, 0, 3, 3, 4, 5, 0, 5, 4, 3, 2, 0, 1, 1, 2, 3,
		 0, 2, 1, 1];
		// 欢乐颂
    	// var keys = [1, 1, 5, 5, 6, 6, 5, 0, 4, 4, 3, 3, 2, 2, 1, 0, 5, 5, 4, 4, 3, 3, 2, 0, 5, 5, 4, 4, 3, 3, 2, 0, 1, 1,5, 5, 6, 6, 5, 0, 4, 4, 3, 3, 2, 2, 1 ];
		var str = '112143 112153 116432 443121';
		var keys = str.split('');
		var count = 0;
		var length = keys.length;
		var timer = setInterval(function() {
			// 下标
			var index = keys[count];
			if (count < length) {
				if (index > 0) {
					buttons[index-1].click();
				}
			} else {
				clearInterval(timer);
			}
			count++;
		},400);
	}
	
</script>